package sg.edu.nus.iss.vmcs.entity.simuator.dao.impl;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public abstract class PropertiesDAOImpl implements sg.edu.nus.iss.vmcs.entity.simuator.dao.IPropertiesDAO {
	
	private Properties properties;
	private File propFle;
	
	public void init(String propPath) 
	throws FileNotFoundException, IOException {
		propFle = new File(propPath);
		if (propFle.exists()) {
			InputStream inputStream = new FileInputStream(propFle);
			properties = new Properties();
			properties.load(inputStream);
		} else {
			propFle.createNewFile();
			properties = new Properties();			
		}
	}
	
	private void reload() 
	throws IOException {
		InputStream inputStream = new FileInputStream(propFle);
		properties = new Properties();
		properties.load(inputStream);
	}
	
	private void store() 
	throws IOException {
		OutputStream outputStream = new FileOutputStream(propFle);
		properties.store(outputStream, "");
		outputStream.close();
	}


	public boolean update(String key, String value) 
	throws IOException {
		properties.setProperty(key, value);
		store();
		System.out.println("The object stored with key ['" + key + "'] updated!");
		reload();
		return true;
	}

	public String findById(String id) 
	throws IOException {
		reload();
		String value = (String) properties.get(id);
		return value;
	}	
	
	public Map<String,String> getKeyValueByAtribute(String attribute) throws IOException{
		int noOfentry = getNumOfItems();
		Map map = new HashMap();
		for(int i =0;i<noOfentry;i++){
			String key = attribute+noOfentry;
			String value = properties.getProperty(key);
			map.put(key, value);			
		}
		return map;
	}
		
	public int getNumOfItems(){
		String nos = properties.getProperty("NumOfItems");
		return Integer.parseInt(nos);
	}
	
    public String getAttributeValue(String key) throws IOException{
    	return properties.getProperty(key);
    }
}